//浏览器访问地址示例：群聊-http://socket.test/socket/app/chat.html?uid=1，uid表示用户id
//私聊-http://socket.test/socket/app/chat.html?uid=1&to_uid=3 表示：当前用户的id是1，要和id为3的用户私聊
var layedit = layui.layedit,
	$ = layui.jquery,
	url = layui.url(),
	param = url.search,
	timer, //定时器
	user_id = param.uid,
	to_uid = param.to_uid,
	testData;//测试数据
layedit.set({
  	uploadImage: {
    	url: 'upload.php', //接口url
  	}
});

var newlayedit = layedit.build('demo', {
	height: 110,
	tool: ['face', 'image']
}); //建立编辑器

let	readyState = 0; //websocket连接状态


if (! "WebSocket" in window) {
	layer.msg('您的浏览器不支持 WebSocket!');
}

//连接服务端
// const ws = new WebSocket('ws://127.0.0.1:8081');
const ws = new WebSocket('ws://10.3.141.169:8081');

//点击按钮断开连接
	$(".close_websocket").click(function () {
	ws.close();
});
/**
 * readyState  返回当前 WebSocket 的链接状态
 * 0 连接中  1连接成功可以通讯  2连接正在关闭  3连接已关闭或者没有链接成功
 */
ws.onopen = function(evt) { 
    readyState = ws.readyState;
    if (readyState != 1) alert('连接失败'); 
    var data = {user_id, 'type' : 'online'};
    sendMsg(data);
};

//接收消息
ws.onmessage = function(evt) {
	// console.log(evt.data);
	let val = JSON.parse(evt.data);
	switch (val.type) {
		case 'online': //上线
			layer.msg(val.content,{
				area: '300px',
				offset: 't',
				time : 1000,
			});
			console.log(val.content);
			break;
		case 'offline'://下线
			layer.msg(val.content,{
				area: '300px',
				offset: 't',
				time : 1000,
			});
			console.log(val.content);
			break;
		case 'heartbeats'://开启心跳检测
			//开启心跳检测
			check_heartbeats(5000);
			break;
		case 'withdraw': //消息撤回
			let message_id = val.message_id;
			$('.'+message_id).remove();
			break;
		case 'broadcast': //广播
			
			break;
		case 'chat':
			$(".message_log_child_div").append(html.other_message(val.content,val.message_id));
			break;
	}
};
//心跳检测
const check_heartbeats = (m = 1000) => {
	timer = setTimeout(function () {
		let text = {'type' : 'heartbeats', 'content' : '检测连接状态'};
		// let text = moment().unix();
		sendMsg(text);
	}, m);
}

ws.onclose = (event) => {
	layer.msg('网络连接失败',{
		area: '300px',
		offset: 't',
		time : 1000,
	});
}

ws.onerror = (event) => layer.msg(event);
	//发送消息
	send_btn_sub.onclick = function () {
		if (ws.readyState != 1) return layer.msg('websocket连接出错');
		let content = layedit.getContent(newlayedit),
			message_id = user_id + '_' +moment().valueOf(),
			field = {user_id, content, 'type' : 'chat', 'chat_type' : 'group_chat', message_id};
			// console.log(to_uid);
		if (to_uid != undefined) {
			field.chat_type = 'private_chat';
			field.to_uid = to_uid;
		}
		sendMsg(field);
		$(".message_log_child_div").append(html.self_message(content,message_id));
		layedit.setContent(newlayedit,'')
	}
/**
 * 将数据转为json并发送
 * @param msg
 */
function sendMsg(msg) {
	
    var res = JSON.stringify(msg);
    ws.send(res);
}
//给自己发的消息添加删除按钮(鼠标移入事件)
function mouseover(self) {
	if ($(self).children().is('.del_message') == false) {
		let code = html.del_message();
		$(self).prepend(code);
	}

}
//将删除按钮删除(鼠标移出事件)
function mouseleave (self) {
	if ($(self).children().is('.del_message') == true) {
		$(self).children(".del_message").remove();
	}
}
//消息撤回
function del_message (self) {
	let message_id = $(self).parent().data('id'),
	data = {'type' : 'withdraw', user_id, message_id};
	sendMsg(data);
	$("."+message_id).remove();
};
//当前聊天房间设置
function chat_setting (self) {
	$(".chat_room_setting").toggle("slow");
}	

const html = {
	time : moment().format('Y/M/d h:mm:ss'),
	//自己发送的消息
	self_message (msg,message_id) {
		let code = `<div class="layui-card message ${message_id}">
					  	<div class="layui-card-header send_time">${moment().format('Y/M/d h:mm:ss')}</div>
					  	<div class="self_headpic_and_content" data-id = "${message_id}" onmouseover = "mouseover(this)" onmouseleave = "mouseleave(this)">
					  		<div class="layui-card-body layui-inline self_user_content">
						    	${msg}
						  	</div>
						  	<div class="layui-card-header layui-inline self_user_headpic">
						  		<div class="user_headpic_div">
						  			<img src="public/images/headpic/self.jpg">
						  		</div>
						  	</div>
					  	</div>
					</div>`;
		return code;
	},
	//别人发送的消息
	other_message (msg, message_id) {
		let code = `<div class="layui-card message ${message_id}" data-id = "${message_id}">
					  	<div class="layui-card-header send_time">${moment().format('Y/M/d h:mm:ss')}</div>
					  	<div class="layui-card-header layui-inline other_user_headpic">
					  		<div class="user_headpic_div">
					  			<img src="public/images/headpic/self.jpg">
					  		</div>
					  	</div>
					  	<div class="layui-card-body layui-inline other_user_content">
					    	${msg}
					  	</div>
					</div>`;
		return code;
	},
	//删除消息图标
	del_message () {
		let code = `<div class="layui-inline del_message" onclick = "del_message(this)">
				  		<a class="layui-icon layui-icon-delete"></a>
				  	</div>`;
		return code;
	},
	//聊天通讯录历史记录
	chat_book_list (data) {
		let code = `<div class="layui-card-header user_div">
				  		<div class="layui-col-md3">
				  			<div class="user_headpic">
				  				<img src="${data.headpic}">
				  			</div>
				  		</div>
				  		<div class="layui-col-md7">
				  			<div class="user_nickname">${data.name}</div>
				  		</div>
				  		<div class="layui-col-md2">
				  			<div class="last_news_time" style="">21/3/15</div>
				  		</div>
				  	</div>`;
		return code;
	},
};